package com.zsc.wxapp.exservices;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.zsc.wxapp.clients.RemotePriceInfoClient;
import com.zsc.wxapp.entity.Product;
import com.zsc.wxapp.entity.external.*;
import com.zsc.wxapp.entity.vo.CigaretteVO;
import com.zsc.wxapp.entity.vo.CustomerVO;
import com.zsc.wxapp.entity.vo.OrderVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@Service
@Slf4j
public class Remote2 {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private RemotePriceInfoClient remotePriceInfoClient;
    private static final String URL = "http://localhost:8082/api/pricetags/getPriceTagsByNamesss";

    public List<Product> getPriceByNames(List<String> names) {
        try {
            String requestJson = new ObjectMapper().writeValueAsString(names);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers);
            ResponseEntity<Product[]> responseEntity = restTemplate.exchange(
                    URL,
                    HttpMethod.POST,
                    requestEntity,
                    Product[].class
            );
            Product[] response = responseEntity.getBody();
            return Arrays.asList(response);
        } catch (Exception e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    private static final String URL_getPriceOverview = "http://localhost:8082/api/pricetags/getPriceOverview";

    public List<PriceOverview> getPriceOverview() {
//        return  remotePriceInfoClient.getPriceOverview();
        HttpHeaders headers = new HttpHeaders();
        HttpEntity<?> requestEntity = new HttpEntity<>(headers);

        // 设置请求头，例如设置内容类型为application/json
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 发送POST请求并接收响应
        ResponseEntity<PriceOverview[]> responseEntity = restTemplate.exchange(
                URL_getPriceOverview,
                HttpMethod.GET, // 使用HTTP POST方法
                requestEntity,
                PriceOverview[].class   // 期望的响应体类型
        );

        // 打印响应状态码
        System.out.println("Response Status Code: " + responseEntity.getStatusCode());

        // 检查响应状态码是否表示成功
        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            // 处理成功的响应，例如打印响应体
            PriceOverview[] priceOverviewArrays = responseEntity.getBody();
//            for (priceOverview priceOverviewArray  : priceOverviewArrays ) {
//                System.out.println(priceOverviewArray ); // 假设Product类有toString方法
//            }
            return Arrays.asList(priceOverviewArrays);
        } else {
            // 处理错误响应
            System.out.println("Failed to get response, status code: " + responseEntity.getStatusCode());
            return null;
        }
    }

    public CustomerInfo getCustomerByCustUuid(String custUuid) {
        try {
            String URL = "http://localhost:8082/api/customers/getByCustUuid";

            String requestJson = new ObjectMapper().writeValueAsString(custUuid);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers);
            ResponseEntity<CustomerInfo> responseEntity = restTemplate.exchange(
                    URL,
                    HttpMethod.POST,
                    requestEntity,
                    CustomerInfo.class
            );
            CustomerInfo response = responseEntity.getBody();
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public CustomerInfo_2 getCustomerByCustUuid_2(String custUuid) {
        try {
            String URL = "http://localhost:8082/api/customers/getByCustUuid_2";

            String requestJson = new ObjectMapper().writeValueAsString(custUuid);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers);
            ResponseEntity<CustomerInfo_2> responseEntity = restTemplate.exchange(
                    URL,
                    HttpMethod.POST,
                    requestEntity,
                    CustomerInfo_2.class
            );
            CustomerInfo_2 response = responseEntity.getBody();
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public List<SalesSummary> getSalesSummaryByCustUuid(String custUuid) {
        try {
            String URL = "http://localhost:8082/api/customers/getOrderByCustUuid";

            String requestJson = new ObjectMapper().writeValueAsString(custUuid);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers);
            ResponseEntity<SalesSummary[]> responseEntity = restTemplate.exchange(
                    URL,
                    HttpMethod.POST,
                    requestEntity,
                    SalesSummary[].class
            );
            SalesSummary[] response = responseEntity.getBody();
            return Arrays.asList(response);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


    public CustomerDetails getCustomerDetailsCustUuid(String custUuid) {
        try {
            String URL = "http://localhost:8082/api/customers/getCustomerDetailsCustUuid";

            String requestJson = new ObjectMapper().writeValueAsString(custUuid);
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers);
            ResponseEntity<CustomerDetails> responseEntity = restTemplate.exchange(
                    URL,
                    HttpMethod.POST,
                    requestEntity,
                    CustomerDetails.class
            );
            CustomerDetails response = responseEntity.getBody();
            return response;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据用户uuid获得用户信息
     *
     * @param custUuid
     * @return CustomerVO
     */
    public CustomerVO getCustomerInfoByCustUuid(String custUuid) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 构建URL，并添加参数
        String param = "custUuid=" + custUuid;
        String url = "http://localhost:8082/api/customers/getCustomInfo?" + param;

        // 创建HttpGet请求
        HttpGet httpGet = new HttpGet(url);

        // 发送请求并获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 获取响应实体
            String jsonResponse = EntityUtils.toString(response.getEntity());

            // 将 JSON 响应转换为 Customer 对象
            ObjectMapper objectMapper = new ObjectMapper();
            CustomerVO customer = objectMapper.readValue(jsonResponse, CustomerVO.class);

            response.close();

            return customer;
        } catch (IOException e) {
            log.error("Error parsing response: " + e.getMessage());
            return null;
        }
    }

    /**
     * 根据用户uuid获取订单信息
     *
     * @param custUuid
     * @return List
     */
    public List<OrderVO> getOrderByCustUuid(String custUuid) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 构建URL，并添加参数
        String param = "custUuid=" + custUuid;
        String url = "http://localhost:8082/api/order/getOrderList?" + param;

        // 创建HttpGet请求
        HttpGet httpGet = new HttpGet(url);

        // 发送请求并获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 获取响应实体
            String jsonResponse = EntityUtils.toString(response.getEntity());

            // 将 JSON 响应转换为 OrderVO 对象
            ObjectMapper objectMapper = new ObjectMapper();
            List<OrderVO> result = objectMapper.readValue(jsonResponse, TypeFactory.defaultInstance().constructCollectionType(List.class, OrderVO.class));

            response.close();

            return result;
        } catch (IOException e) {
            log.error("Error parsing response: " + e.getMessage());
            return null;
        }
    }

    /**
     * 根据名称查询卷烟信息
     *
     * @param name
     * @return Product
     */
    public Product getCigaretteByName(String name) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 构建URL，并添加参数
        String url = "http://localhost:8082/api/cigarette/getCigaretteByName";

        // 创建HttpGet请求
        HttpGet httpGet = new HttpGet(url);

        //设置参数
        try {
            name = URLEncoder.encode(name, String.valueOf(StandardCharsets.UTF_8));
        } catch (UnsupportedEncodingException e) {
            log.error("编码失败，本次要编码的内容是：{}", name);
            return null;
        }
        httpGet.setHeader("name", name);

//        log.info("name:{}", name);
//        log.info("httpGet:{}", httpGet.getHeaders("name"));

        // 发送请求并获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 获取响应实体
            String jsonResponse = EntityUtils.toString(response.getEntity());

            // 将 JSON 响应转换为 Product 对象
            ObjectMapper objectMapper = new ObjectMapper();
            Product result = objectMapper.readValue(jsonResponse, Product.class);

            response.close();

            return result;
        } catch (IOException e) {
            log.error("Error parsing response: " + e.getMessage());
            return null;
        }
    }

    /**
     * 获取用户最近一次的订单中的卷烟代码
     *
     * @param customUuid
     * @return List
     */
    public List<OrderVO> getLastOrderListByCustUuid(String customUuid) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 构建URL，并添加参数
        String param = "customUuid=" + customUuid;
        String url = "http://localhost:8082/api/order/getOrderListByCustUuid?" + param;

        // 创建HttpGet请求
        HttpGet httpGet = new HttpGet(url);

        // 发送请求并获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 获取响应实体
            String jsonResponse = EntityUtils.toString(response.getEntity());

            // 将 JSON 响应转换为 OrderVO 对象
            ObjectMapper objectMapper = new ObjectMapper();
            List<OrderVO> result = objectMapper.readValue(jsonResponse, TypeFactory.defaultInstance().constructCollectionType(List.class, OrderVO.class));

            response.close();

            return result;
        } catch (IOException e) {
            log.error("Error parsing response: " + e.getMessage());
            return null;
        }
    }

    /**
     * 根据code获取卷烟信息
     *
     * @param productCode
     * @return CigaretteVO
     */
    public CigaretteVO getByCode(String productCode) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 构建URL，并添加参数
        String param = "productCode=" + productCode;
        String url = "http://localhost:8082/api/cigarette/getByCode?" + param;

        // 创建HttpGet请求
        HttpGet httpGet = new HttpGet(url);

        // 发送请求并获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 获取响应实体
            String jsonResponse = EntityUtils.toString(response.getEntity());

            // 将 JSON 响应转换为 OrderVO 对象
            ObjectMapper objectMapper = new ObjectMapper();
            CigaretteVO result = objectMapper.readValue(jsonResponse, CigaretteVO.class);

            response.close();

            return result;
        } catch (IOException e) {
            log.error("Error parsing response: " + e.getMessage());
            return null;
        }
    }

    public List<CustomerVO> test(List<String> test) {

        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 构建URL，并添加参数
        String url = "http://localhost:8082/api/customers/getCustomerByLicenseCode";

        // 创建HttpGet请求
        HttpGet httpGet = new HttpGet(url);

        //设置参数
//        try {
//            custCode = URLEncoder.encode(custCode, String.valueOf(StandardCharsets.UTF_8));
//        } catch (UnsupportedEncodingException e) {
//            log.error("编码失败，本次要编码的内容是：{}", custCode);
//            return null;
//        }
        httpGet.setHeader("custCode", test.toString());

        log.info("custCode:{}", test.toString());
        log.info("httpGet:{}", httpGet.getHeaders("name"));

        // 发送请求并获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 获取响应实体
            String jsonResponse = EntityUtils.toString(response.getEntity());

            // 将 JSON 响应转换为 Product 对象
            ObjectMapper objectMapper = new ObjectMapper();
            List<CustomerVO> result = objectMapper.readValue(jsonResponse, TypeFactory.defaultInstance().constructCollectionType(List.class, CustomerVO.class));

            response.close();

            return result;
        } catch (IOException e) {
            log.error("Error parsing response: " + e.getMessage());
            return null;
        }
//        return null;
    }

    public List<CustomerVO> getAllCustomer() {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 构建URL，并添加参数
        String url = "http://localhost:8082/api/customers/getAllCustomer";

        // 创建HttpGet请求
        HttpGet httpGet = new HttpGet(url);

        // 发送请求并获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 获取响应实体
            String jsonResponse = EntityUtils.toString(response.getEntity());

            // 将 JSON 响应转换为 Product 对象
            ObjectMapper objectMapper = new ObjectMapper();
            List<CustomerVO> result = objectMapper.readValue(jsonResponse, TypeFactory.defaultInstance().constructCollectionType(List.class, CustomerVO.class));

            response.close();

            return result;
        } catch (IOException e) {
            log.error("Error parsing response: " + e.getMessage());
            return null;
        }
    }

    public String getManagerByName(String name) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 构建URL，并添加参数
        String url = "http://localhost:8082/api/customers/getMangerUuid";

        // 创建HttpGet请求
        HttpGet httpGet = new HttpGet(url);

        //设置参数
        try {
            name = URLEncoder.encode(name, String.valueOf(StandardCharsets.UTF_8));
        } catch (UnsupportedEncodingException e) {
            log.error("编码失败，本次要编码的内容是：{}", name);
            return null;
        }
        httpGet.setHeader("name", name);

        // 发送请求并获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 获取响应实体
            String result = EntityUtils.toString(response.getEntity());

            response.close();

            return result;
        } catch (IOException e) {
            log.error("Error parsing response: " + e.getMessage());
            return null;
        }
    }

    /**
     * 根据许可证号获取用户信息
     * @param licenseCode
     * @return
     */
    public CustomerVO getCustomerByLicenseCode(String licenseCode) {
        // 创建HttpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();

        // 构建URL，并添加参数
        String url = "http://localhost:8082/api/customers/getCustomerByLicenseCode";

        //设置参数
        url = url + "?licenseCode=" + licenseCode;

        // 创建HttpGet请求
        HttpGet httpGet = new HttpGet(url);

        // 发送请求并获取响应
        try {
            CloseableHttpResponse response = httpClient.execute(httpGet);

            // 获取响应实体
            String jsonResponse = EntityUtils.toString(response.getEntity());

            // 将 JSON 响应转换为 Product 对象
            ObjectMapper objectMapper = new ObjectMapper();
            CustomerVO result = objectMapper.readValue(jsonResponse, CustomerVO.class);

            response.close();

            return result;
        } catch (IOException e) {
            log.error("Error parsing response: " + e.getMessage());
            return null;
        }
    }
}
